<template>
  <el-card class="box-card">
    <template #header>
    <!-- card卡片 -->
      <div class="card-header">
        <el-button type="primary" :icon="Plus" @click="showTrademarkDialog">添加</el-button>  
      </div>
    </template>
    <div> 
    <!-- table表格 -->
    <el-table
    v-loading="loading" 
    :data="tradeMarkList" 
    border 
    style="width: 100%;margin-bottom:20px">
      <el-table-column  type="index"  align= 'center' label="序号" width="180" />
    <el-table-column prop="tmName" label="品牌" />
    <el-table-column prop="name" label="品牌LOGO">

    <!-- table-column插槽属性 -->
      <template v-slot="{row}">
          <img :src="row.logoUrl" alt="" style="width:100px">
      </template>
    </el-table-column>
    <el-table-column prop="address" label="操作" >
    <template v-slot="{row}">
      <el-tooltip
        class="box-item"
        effect="dark"
        content="编辑"
        placement="top"
      >
        <el-button type="warning" size="small" :icon="Edit" @click="toEditTrademarkInfo(row)"/>
      </el-tooltip>

      <el-tooltip
        class="box-item"
        effect="dark"
        content="删除"
        placement="top"
      >
      <el-button type="danger" size="small" :icon="Delete"
        @click="toRemoveTrademark(row.id)"
         />
        </el-tooltip>
      </template>
      </el-table-column>
  </el-table>
  </div>

   <!-- 分页器 -->
  <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout=" prev, pager, next,jumper,->,sizes,total"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 弹出添加对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="`${trademarkInfo.id?'编辑':'添加'}品牌`">
    <el-form 
    :model="trademarkInfo"  
    ref="trademarkFormRef"  
    :rules="rules">
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input v-model="trademarkInfo.tmName" autocomplete="off" style="width:300px" />
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        
  <el-upload
    class="avatar-uploader"
    :action="`${BASE_URL}/admin/product/upload`"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="trademarkInfo.logoUrl" :src="trademarkInfo.logoUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    <template #tip>
      <div class="el-upload__tip">
       只能上传jpg/png格式图片,且大小不能超过2MB
      </div>
    </template>
  </el-upload>

      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary"
        @click="btnTrademark(trademarkFormRef)"
          >确认</el-button
        >
      </span>
    </template> 
  </el-dialog>
  </el-card>


</template>

<script  lang="ts">
import { Plus, Edit, Delete} from '@element-plus/icons-vue'
import { reqGetTradeMarkList,reqSaveTrademarkInfo,reqRemoveTrademarkInfo,reqUpdateTrademarkInfo  } from '@/api/product/trademark'
import { onMounted, ref,reactive } from 'vue'
import type { TrademarkListModel,TradeMarkModel } from '@/api/model/trademarkModel'
import { ElMessage, ElMessageBox  } from 'element-plus'
import type { UploadProps } from 'element-plus'
import type { FormInstance,FormRules } from 'element-plus'

const trademarkFormRef  = ref<FormInstance>()


export default {
  name: "Trademark",
};
</script>

<script lang="ts" setup>
// 加载定义true
const loading = ref(true)

//定义初始数据
let tradeMarkList = ref<TrademarkListModel>([])
let currentPage = ref(1)
let pageSize = ref(3)
let total = ref(0)
const small = ref(false)
const disabled = ref(false)
const background = ref(false)


// 添加数据初始化
const dialogFormVisible = ref(false)
// const form = reactive<TradeMarkModel>({
//   tmName:'',
//   logoUrl:''
// })

const imageUrl = ref('')
const BASE_URL = import.meta.env.VITE_API_URL
const initTrademarkInfo = () => ({
  tmName: '',
  logoUrl: ''
});


// 数据校验规则的定义
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { min: 2, max: 6, message: '长度在2-6个字符之间', trigger: 'blur' },
  ],
  logoUrl : [
    {
      required: true,
      message: '请至少上传一张图片',
      trigger: 'change',
    },
  ],
})



const trademarkInfo = reactive<TradeMarkModel>(initTrademarkInfo());


// 一挂载就要渲染列表
onMounted(()=>{
  getTradeMarkList()
})

const getTradeMarkList= async ()=>{
  const res = await reqGetTradeMarkList(currentPage.value,pageSize.value)
  tradeMarkList.value = res.records
  total.value = res.total
  console.log(tradeMarkList);

  // 加载完成后要变false
  loading.value = false
   
};

// 当前页跳转的响应
const handleCurrentChange = (val: number)=>{
  currentPage.value = val
  getTradeMarkList()
}

//一页多少条的响应
const handleSizeChange = (val: number)=>{
  pageSize.value = val
  currentPage.value = 1
  getTradeMarkList()
}

// <!-- 上传图片前的校验 -->

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const imgTypes = ['image/jpeg','image/jpg','image/png']
  if (!imgTypes.includes(rawFile.type)) {
    ElMessage.error('上传图片的格式只能是jpg/png/jepg,请重新选择')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2M,请重新选择...!')
    return false
  }
  return true
};

// 校验图片成功后
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  console.log(response,uploadFile);
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  trademarkInfo.logoUrl = response.data
  // 清除图片的校验提示
  trademarkFormRef.value?.clearValidate(['logoUrl'])
}

//添加品牌
const btnTrademark=async (formEl: FormInstance | undefined)=>{
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if(valid){
        if (trademarkInfo.id) {
           await reqUpdateTrademarkInfo(trademarkInfo)
         } else {
             await reqSaveTrademarkInfo(trademarkInfo)
     currentPage.value = 1
    }
 
  ElMessage.success('操作 品牌成功了')
 
  dialogFormVisible.value = false
  // 重新刷新页面
  getTradeMarkList()
}else{
  console.log('error submit!', fields);
}
})
}


//清除之前的数据
const showTrademarkDialog=()=>{
  // trademarkInfo.logoUrl='',
  // trademarkInfo.tmName='',
  // imageUrl.value=''
   // 清除校验提示
   trademarkFormRef.value?.clearValidate()
  Object.assign(trademarkInfo, initTrademarkInfo());
  // 删除更新时的id 
  delete trademarkInfo.id
  dialogFormVisible.value = true
}

//删除品牌
const toRemoveTrademark = (id: number)=>{   
  ElMessageBox.confirm(
    '您真的要删除吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(  async()=>{
   await reqRemoveTrademarkInfo(id) 
  // 重新刷新页面
    getTradeMarkList()
      ElMessage({
        type: 'success',
        message: '删除品牌成功了',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
};
// 编辑
const toEditTrademarkInfo=(row:TradeMarkModel)=>{
  // 合并数据，实现数据回显  
  Object.assign(trademarkInfo,row)
  dialogFormVisible.value = true
   // 清除图片的校验提示
   trademarkFormRef.value?.clearValidate()
}
 
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
